<?php
require_once 'Translator/Model.php';

/**
 * Class used to access the phpBB user data.
 * 
 * @remark: This class is used for authentication and should be used
 * for NOTHING else.
 */
class ForumUserModel extends Translator_Model {
	private $_dbName;
	private $_dbPrefix;
	
	/**
	 * Store forum configuration data as attributes for easier access.
	 */
	public function __construct() {
		parent::__construct();
		
		$options = Zend_Registry::get('phpBB');
		$this->_dbName = $options['dbname'];
		$this->_dbPrefix = $options['dbprefix'];
	}
	
	/**
	 * Fetch the username of this user.
	 * 
	 * @param int $userid
	 */
	public function fetchUsername($userid) {
		return $this->_db->fetchOne(
			'SELECT username 
			 FROM '.$this->table('users').' 
			 WHERE user_id = ?
			 LIMIT 1',
			array($userid)
		);
	}
	
	/**
	 * Fetch user entry by username
	 * @param string $username
	 */
	public function fetchByUsername($username) {
		return $this->_db->fetchRow(
			'SELECT user_id, user_email, user_password, user_pass_convert, user_type, user_login_attempts
			 FROM '.$this->table('users').'
			 WHERE username = ?
			 LIMIT 1',
			array($username)
		);
	}
	
	/**
	 * Reset the login attempts of the given user
	 */
	public function resetLoginAttempts($userid) {
		$this->_db->update(
			$this->table('users'), 
			array('user_login_attempts' => 0), 
			'user_id = '.intval($userid)
		);
	}
	
	/**
	 * Increase number of login attempts.
	 */
	public function increaseLoginAttempts($userid) {
		$this->_db->update(
			$this->table('users'), 
			array('user_login_attempts' => new Zend_Db_Expr('user_login_attempts + 1')), 
			'user_id = '.intval($userid)
		);
	}
	
	/**
	 * Constructs the table identifier taking into consideration that
	 * the forum is usually in another database than the rest of the
	 * system and that tables may have a prefix. 
	 * 
	 * @param string $name Original name of the table
	 */
	private function table($name) {
		return $this->_dbName.'.'.$this->_dbPrefix.$name;
	}
}